package password

import (
	"code.google.com/p/go.crypto/bcrypt"
	"code.google.com/p/jesus-1496/settings"
	"encoding/base64"
	"errors"
	"fmt"
)

func newPasswordError(errorString string) error {
	return errors.New(fmt.Sprintf("PasswordError: %s", errorString))
}

func ValidatePassword(pw string) error {
	if len(pw) < settings.Settings.Auth.MinPasswordLength || len(pw) > settings.Settings.Auth.MaxPasswordLength {
		return newPasswordError(fmt.Sprintf("Password must be in-between %v and %v.", settings.Settings.Auth.MinPasswordLength, settings.Settings.Auth.MaxPasswordLength))
	}
	return nil
}

func GenerateHashInputFromStrings(strings ...string) ([]byte, error) {
	hashInput := make([]byte, 0)
	for _, s := range strings {
		sBytes := []byte(s)
		hashInput = append(hashInput, sBytes...)
	}
	return hashInput, nil
}

func GenerateHash(b []byte) (string, error) {
	hash, err := bcrypt.GenerateFromPassword(b, settings.Settings.Auth.BcryptCost)
	if err != nil {
		return "", err
	}
	return base64.StdEncoding.EncodeToString(hash), nil
}

func CompareHashAndInput(hash string, input []byte) error {
	hashBlob, err := base64.StdEncoding.DecodeString(hash)
	if err != nil {
		return err

	}
	return bcrypt.CompareHashAndPassword(hashBlob, input)
}
